﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpAlgorithm
{
    class BoxFactory
    {
        public BoxFactory()
        {
            int testCount = Int32.Parse(TestConsole.ReadLine());
            for (int testCase = 1; testCase <= testCount; testCase++)
            {
                string[] input = TestConsole.ReadLine().Split(' ');
                int boxCount = Int32.Parse(input[0]);
                int toyCount = Int32.Parse(input[1]);
                long[,] boxList = new long[boxCount + 1, 2];
                input = TestConsole.ReadLine().Split(' ');
                for (int i = 1; i <= boxCount * 2; i += 2)
                {
                    boxList[i / 2 + 1, 0] = long.Parse(input[i - 1]);
                    boxList[i / 2 + 1, 1] = long.Parse(input[i]);
                }
                long[,] toyList = new long[toyCount + 1, 2];
                input = TestConsole.ReadLine().Split(' ');
                for (int j = 1; j <= toyCount * 2; j += 2)
                {
                    toyList[j / 2 + 1, 0] = long.Parse(input[j - 1]);
                    toyList[j / 2 + 1, 1] = long.Parse(input[j]);
                }
                long[,] dp = new long[boxCount + 1, toyCount + 1];
                long[,] restBox = new long[boxCount + 1, toyCount + 1];
                for (int i = 1; i <= boxCount; i++)
                {
                    restBox[i, 0] = boxList[i, 0];
                }
                long[,] restToy = new long[toyCount + 1, toyCount + 1];
                for (int j = 1; j <= toyCount; j++)
                {
                    restToy[0, j] = toyList[j, 0];
                }
                for (int i = 1; i <= boxCount; i++)
                {
                    for (int j = 1; j <= toyCount; j++)
                    {
                        restBox[i, j] = restBox[i, j - 1];
                        restToy[i, j] = restToy[i - 1, j];
                        if (boxList[i, 1] == toyList[j, 1])
                        {
                            long value = Math.Min(restBox[i, j], restToy[i, j]);
                            dp[i, j] += Math.Max(dp[i, j - 1], dp[i - 1, j]) + value;
                            restBox[i, j] -= value;
                            restToy[i, j] -= value;
                        }
                        else
                        {
                            dp[i, j] = Math.Max(dp[i, j - 1], dp[i - 1, j]);
                        }
                    }
                }
                Console.WriteLine("Case #" + testCase + ": " + dp[boxCount, toyCount]);
            }
        }
    }
}
